<template>
  <el-drawer
    title="预览"
    direction="rtl"
    :visible.sync="innerVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    size="80%"
    :append-to-body="false"
    :wrapper-closable="!loading"
    @close="closeDialog()"
  >
    <template slot="title">
      <el-row type="flex" align="center">
        <el-col :span="12">预览</el-col>
        <el-col :span="12" style="display: flex; justify-content: right">
          <el-date-picker
            v-model="comparisonDateRange"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            style="margin-right: 10px"
            @change="comparisonDateRangeChange"
          />
          <el-button
            type="primary"
            icon="el-icon-download"
            :loading="loading"
            size="small"
            @click="downloadCharImage"
          >
            下载当前页图
          </el-button>
          <!--          <el-button-->
          <!--            type="primary"-->
          <!--            icon="el-icon-download"-->
          <!--            :loading="loading"-->
          <!--            size="small"-->
          <!--            @click="download"-->
          <!--          >-->
          <!--            下载PDF-->
          <!--          </el-button>-->
          <el-button
            icon="el-icon-close"
            size="small"
            :disabled="loading"
            @click="cancel"
          >
            关闭
          </el-button>
        </el-col>
      </el-row>
    </template>
    <el-carousel
      ref="carousel"
      trigger="click"
      :autoplay="false"
      indicator-position="none"
      arrow="always"
      height="calc(100vh - 88px)"
      v-loading="loading"
    >
      <el-carousel-item v-if="showObj.zl" name="qualityScore" label="qualityScore">
        <div ref="container1" class="wrapper">
          <div ref="textContainer" class="text-container">
            <div class="text-title fontBold">
              <div class="text-underline">精装</div>抽查成绩（<span style="font-weight: normal">检查日期：</span><span style="color: red">{{ current.checkDate }}</span>）
            </div>
            <div class="text-title fontBold" style="margin-bottom: 10px">
              {{ dataFormat.deptName }}-<div v-if="current.projectName" class="text-underline">{{ current.projectName }}</div>
            </div>
            <div class="text-content">
              <span class="fontBold">1、第一责任人（集群/事业部）：</span><span style="margin-right: 10px">{{ dataFormat.principalName }}</span>
              <span class="fontBold">2、项目总：</span><span style="margin-right: 10px">{{ current.xmzName || '/' }}</span>
              <span class="fontBold">3、精装项目经理：</span><span style="margin-right: 10px">{{ current.xmjlName || '/' }}</span>
              <span class="fontBold">4、精装总包：</span><span style="margin-right: 10px">{{ constructionName || '/' }}</span>
            </div>
            <div class="text-content fontBold">
              5、检查成绩：
            </div>
            <div class="text-section-container">
              <div
                v-for="(section, index) in sections"
                :key="index"
                class="text-section-item"
              >
                <div class="text-content">
                  {{ section.sectionName ? `${section.constructionName}（${section.sectionName}）` : section.constructionName }}：
                </div>
                <div class="text-content">
                  ①防渗漏：{{ section['GC-001-002-001_level'] ? section['GC-001-002-001_level']: '/' }}<span v-if="section['GC-001-002-001_level']">（<span :style="{ color: section['GC-001-002-001_level'] === 'A' ? '#00AF4D' : 'red' }">{{ section['GC-001-002-001_level'] === 'A' ? '合格' : '不合格' }}</span>）</span>
                </div>
                <div class="text-content">
                  ②质量：{{ section['GC-001-002-002_score'] ? section['GC-001-002-002_score'] : '/' }}<span v-if="section['GC-001-002-002_score']">（<span :style="{ color: section['GC-001-002-002_level'] !== 'C' ? '#00AF4D' : 'red' }">{{ levelLabelMap[section['GC-001-002-002_level']] }}</span>）</span>
                </div>
                <div class="text-content">
                  ③安全文明： {{ section['GC-001-002-003_score'] ? section['GC-001-002-003_score']: '/' }}<span v-if="section['GC-001-002-003_score']">（<span :style="{ color: section['GC-001-002-003_level'] !== 'C' ? '#00AF4D' : 'red' }">{{ levelLabelMap[section['GC-001-002-003_level']] }}</span>）</span>
                </div>
              </div>
            </div>
          </div>
          <div ref="qualityChart" class="char-container" />
        </div>
      </el-carousel-item>
      <el-carousel-item v-if="showObj.aqwm" name="safetyProductionScore" label="safetyProductionScore">
        <div ref="container2" class="wrapper">
          <div ref="textContainer" class="text-container">
            <div class="text-title fontBold">
              <div class="text-underline">精装</div>抽查成绩（<span style="font-weight: normal">检查日期：</span><span style="color: red">{{ current.checkDate }}</span>）
            </div>
            <div class="text-title fontBold" style="margin-bottom: 10px">
              {{ dataFormat.deptName }}-<div v-if="current.projectName" class="text-underline">{{ current.projectName }}</div>
            </div>
            <div class="text-content">
              <span class="fontBold">1、第一责任人（集群/事业部）：</span><span style="margin-right: 10px">{{ dataFormat.principalName }}</span>
              <span class="fontBold">2、项目总：</span><span style="margin-right: 10px">{{ current.xmzName || '/' }}</span>
              <span class="fontBold">3、精装项目经理：</span><span style="margin-right: 10px">{{ current.xmjlName || '/' }}</span>
              <span class="fontBold">4、精装总包：</span><span style="margin-right: 10px">{{ constructionName || '/' }}</span>
            </div>
            <div class="text-content fontBold">
              5、检查成绩：
            </div>
            <div class="text-section-container">
              <div
                v-for="(section, index) in sections"
                :key="index"
                class="text-section-item"
              >
                <div class="text-content">
                  {{ section.sectionName ? `${section.constructionName}（${section.sectionName}）` : section.constructionName }}：
                </div>
                <div class="text-content">
                  ①防渗漏：{{ section['GC-001-002-001_level'] ? section['GC-001-002-001_level']: '/' }}<span v-if="section['GC-001-002-001_level']">（<span :style="{ color: section['GC-001-002-001_level'] === 'A' ? '#00AF4D' : 'red' }">{{ section['GC-001-002-001_level'] === 'A' ? '合格' : '不合格' }}</span>）</span>
                </div>
                <div class="text-content">
                  ②质量：{{ section['GC-001-002-002_score'] ? section['GC-001-002-002_score'] : '/' }}<span v-if="section['GC-001-002-002_score']">（<span :style="{ color: section['GC-001-002-002_level'] !== 'C' ? '#00AF4D' : 'red' }">{{ levelLabelMap[section['GC-001-002-002_level']] }}</span>）</span>
                </div>
                <div class="text-content">
                  ③安全文明： {{ section['GC-001-002-003_score'] ? section['GC-001-002-003_score']: '/' }}<span v-if="section['GC-001-002-003_score']">（<span :style="{ color: section['GC-001-002-003_level'] !== 'C' ? '#00AF4D' : 'red' }">{{ levelLabelMap[section['GC-001-002-003_level']] }}</span>）</span>
                </div>
              </div>
            </div>
          </div>
          <div ref="sgaqChart" class="char-container" />

        </div>
      </el-carousel-item>
    </el-carousel>

  </el-drawer>
</template>

<script>
import * as echarts from 'echarts'
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
import {getReportPreviewData} from '@/api/checkScore/courseCheck'

export default {
  name: 'ReportPreview',
  components: {
  },
  filters: {
    valueQualified(val) {
      return val !== 'C'
    }
  },
  props: {
  },
  data() {
    return {
      innerVisible: false,
      loading: false,
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ]
      },
      checkShowFields: [],
      indexMap: {
        0: '①', 1: '②', 2: '③', 3: '④'
      },
      showObj: {
        zl: false,
        aqwm: false
      },
      reportData: {},
      current: {},
      comparisonDateRange: [],
      pickerOptions: {},
      sections: [],
      levelLabelMap: {
        A: '优秀', B: '合格', C: '不合格'
      },
      constructionName: ''
    }
  },
  computed: {
    dataFormat() {
      const data = this.current
      const deptNames = []
      const clusterName = data.deptName1 || ''
      if (clusterName) {
        deptNames.push(clusterName.indexOf('集群') ? clusterName : clusterName + '集群')
      }
      const divisionName = data.deptName2 || ''
      if (divisionName) {
        deptNames.push(divisionName.indexOf('事业部') ? divisionName : divisionName + '事业部')
      }
      const cityCorporationName = data.deptName3 || ''
      if (cityCorporationName) {
        deptNames.push(cityCorporationName.indexOf('城市公司') ? cityCorporationName : cityCorporationName + '城市公司')
      }
      const principalNames = []
      if (data.colonyName) {
        principalNames.push(data.colonyName)
      }
      if (data.businessName) {
        principalNames.push(data.businessName)
      }
      return { deptName: deptNames.join('-'), principalName: principalNames.length === 0 ? '/' : principalNames.join('/') }
    },
    checkDate() {
      let result = '-'
      const checkDate = this.current.checkDate
      if (checkDate) {
        result = this.parseTime(checkDate, '{y}.{m}.{d}')
      }
      return result
    }
  },
  watch: {},
  created() {
  },
  methods: {
    async init(current) {
      this.innerVisible = true
      this.current = current
      const currentTime = new Date()
      let year = parseInt(this.parseTime(currentTime, '{y}'))
      if (currentTime.getTime() < new Date(`${year}-12-26`).getTime()) {
        year--
      }
      this.comparisonDateRange = [`${year}-12-26`, `${year + 1}-12-25`]
      this.checkShowFields = this.getCheckShowFields(current)
      await this.queryComparisonData(current, this.comparisonDateRange)
    },
    /**
     * 判断是否合格
     * @param val
     * @return {boolean}
     */
    valueQualified(val) {
      return val !== 'C'
    },
    /**
     * 对比时间改变
     * @param value
     */
    comparisonDateRangeChange(value) {
      this.queryComparisonData(this.current, value)
    },
    /**
     * 查询对比数据
     * @param current
     * @param comparisonDateRange
     * @return {Promise<void>}
     */
    async queryComparisonData(current, comparisonDateRange) {
      if (this.loading || comparisonDateRange.length !== 2) {
        return
      }
      this.loading = true
      const res = await getReportPreviewData({ prjchkId: current.prjchkId, startDate: comparisonDateRange[0], endDate: comparisonDateRange[1] }).catch(err => {
        console.log(err)
        this.$message.error('请求报表数据异常')
      }).finally(_ => {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      })
      const chartData = res && res.code === 200 ? res.data : {}
      this.sections = chartData.section
      const taskIds = chartData.section.map(item => item.prjchkId)
      this.constructionName = chartData.section.map(item => item.constructionName).join('、')

      // 质量
      if (chartData['GC-001-002-002_score'].length) {
        this.showObj.zl = true
        this.$nextTick(() => {
          this.renderChartData(this.$refs.qualityChart, chartData['GC-001-002-002_score'], taskIds, '集团质量得分情况')
        })
      }
      // 施工安全
      if (chartData['GC-001-002-003_score'].length) {
        this.showObj.aqwm = true
        this.$nextTick(() => {
          this.renderChartData(this.$refs.sgaqChart, chartData['GC-001-002-003_score'], taskIds, `集团精装安全文明得分情况`)
        })
      }
    },
    /**
     * 处理图表数据
     * @param el
     * @param list
     * @param taskIds
     * @param title
     */
    renderChartData(el, list = [], taskIds = [], title) {
      const echart = echarts.init(el)
      console.log(echart.getHeight())
      const allowMaxRows = Math.floor(echart.getHeight() * 0.4 / 12)
      const rowCounts = []
      const qualified = []
      const unQualified = []

      for (const item of list) {
        item.score = item.score <= 0 ? 0 : item.score
        if (item.qualified) {
          qualified.push(item)
        } else {
          unQualified.push(item)
        }
        const { value, rowCount } = this.xAxisLabelFormatter(item.projectName, allowMaxRows)
        item.projectName = value
        rowCounts.push(rowCount)
      }

      qualified.sort((a, b) => b.score - a.score)
      unQualified.sort((a, b) => b.score - a.score)
      const maxRows = Math.max.apply(null, rowCounts)
      const data = qualified.concat(unQualified)
      // const offset = qualified.length === 0 || unQualified.length === 0 ? 0 : (Math.ceil(qualified.length / data.length * chartWidth) + 15)
      const constructionXAxis = []
      const constructionValues = []
      let minValue = 100
      data.forEach(item => {
        const value = item.score
        const valueItem = { value: value}
        if (taskIds.includes(item.taskId)) {
          valueItem.itemStyle = { color: '#EE7D31' }
        }
        if (!item.qualified) {
          valueItem.label = { color: 'red' }
        }
        constructionXAxis.push(item.projectName)
        constructionValues.push(valueItem)
        if (value < minValue) {
          minValue = value
        }
      })
      const option = this.getOption(title, constructionXAxis, constructionValues, maxRows * 12 + 10, minValue)
      echart.resize()
      echart.setOption(option)
    },
    /**
     * 获取chart配置
     * @param title
     * @param xAxis
     * @param values
     * @param bottom
     * @param minValue
     * @return {{yAxis: {min: number, max: number, type: string}, xAxis: {axisLabel: {interval: number, fontSize: number}, data: *[], axisTick: {show: boolean}, type: string}, grid: {left: number, bottom: number, right: number}, series: [{barWidth: string, barMaxWidth: string, data: *[], barMinWidth: string, itemStyle: {color: string}, label: {show: boolean, position: string}, type: string, markLine: {symbol: string[], silent: boolean, data: [{yAxis: number, lineStyle: {color: string}, name: string, label: {formatter: string, distance: number[], color: string, position: string}}]}}], textStyle: {fontFamily: string, color: string}, title: {left: string, text: string, textStyle: {fontFamily: string, color: string}}}}
     */
    getOption(title = '', xAxis = [], values = [], bottom = 0, minValue) {
      return {
        textStyle: {
          color: '#000',
          fontFamily: 'Simsun'
        },
        title: {
          text: title,
          left: 'center',
          textStyle: {
            color: '#000',
            fontFamily: 'Simsun'
          },
          subtext: '（注：红色数值标识为不合格）',
          subtextStyle: {
            color: 'red'
          }
        },
        grid: {
          top: 70,
          left: 30,
          right: 0,
          bottom: bottom
        },
        xAxis: {
          type: 'category',
          data: xAxis,
          axisLabel: {
            interval: 0,
            fontSize: 12
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          min: minValue > 70 ? 70 : parseInt((minValue / 10).toString()) * 10,
          max: 100
        },
        series: [{
          type: 'bar',
          label: {
            show: true,
            position: 'top'
          },
          itemStyle: {
            color: '#5B9CD6'
          },
          barWidth: '30%',
          barMaxWidth: '40%',
          barMinWidth: '20%',
          markLine: {
            silent: false,
            symbol: ['none', 'none'],
            data: [{
              name: '线',
              yAxis: 80,
              lineStyle: {
                color: '#00AF4D',
                width: 2
              },
              label: {
                distance: [0, 50],
                formatter: '合格：{c}',
                position: 'insideEndTop',
                color: '#00AF4D'
              }
            }]
          },
          data: values
        }]
      }
    },
    /**
     * X轴内容格式化
     * @param value
     * @return {string|{rowCount: number, value: string}}
     */
    xAxisLabelFormatter(value, maxRows) {
      // const specialChars = value.match(/[^\u4e00-\u9fa5]/g)
      // const chars = []
      // if (specialChars && specialChars.length > 0 && specialChars[0] !== '、') {
      //   const specialStr = specialChars.join('')
      //   const strings = value.split(specialStr)
      //   chars.push(...strings[0].split(''))
      //   const specials = specialStr.split('、')
      //   specials.forEach((special, index) => {
      //     chars.push(special)
      //     if (index < specials.length - 1) {
      //       chars.push('、')
      //     }
      //   })
      //   if (strings[1]) {
      //     chars.push(...strings[1].split(''))
      //   }
      // } else {
      //   chars.push(...value.split(''))
      // }
      let chars = []
      const length = value.length
      if (length > maxRows) {
        const rows = Math.ceil(length / maxRows)
        for (let i = 0; i < length; i = i + rows) {
          chars.push(value.substring(i, i + rows))
        }
      } else {
        chars = value.split(/[\t\r\f\n\s]*/g)
      }
      return { value: chars.join('\n'), rowCount: chars.length }
    },
    /**
     * 关闭窗口
     */
    closeDialog() {
      this.current = {}
      this.innerVisible = false
    },
    /**
     * 取消操作
     */
    cancel() {
      this.closeDialog()
    },
    /**
     * 下载
     */
    async download() {
      this.loading = true
      const pdf = new JsPDF('l', 'pt', 'a4')
      const current = this.current
      try {
        if (current.groupActionScore) {
          await html2canvas(this.$refs.container0, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            const imgWidth = 595.28 / contentHeight * contentWidth
            const imgHeight = 595.28
            const pageData = canvas.toDataURL('image/jpeg', 1.0)
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          })
        }
        if (current.qualityScore) {
          pdf.addPage()
          await html2canvas(this.$refs.container1, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            const imgWidth = 595.28 / contentHeight * contentWidth
            const imgHeight = 595.28
            const pageData = canvas.toDataURL('image/jpeg', 1.0)
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          })
        }
        if (current.safetyProductionScore || current.constructionScore) {
          pdf.addPage()
          await html2canvas(this.$refs.container2, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
            const imgWidth = 595.28 / contentHeight * contentWidth
            const imgHeight = 595.28
            const pageData = canvas.toDataURL('image/jpeg', 1.0)
            pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
          })
        }
        pdf.save('飞检成绩.pdf')
      } catch (e) {
        this.$message.error('下载失败')
      } finally {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      }
    },
    download2() {
      this.loading = true
      const pdf = new JsPDF('l', 'pt', 'a4')
      const promises = [
        new Promise((resolve, reject) => {
          html2canvas(this.$refs.container0, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            debugger
            resolve({
              base64: canvas.toDataURL('image/jpeg', 1.0),
              height: 595.28,
              width: 595.28 / contentHeight * contentWidth
            })
          }).catch(err => {
            reject(err)
          })
        }),
        new Promise((resolve, reject) => {
          html2canvas(this.$refs.container1, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            debugger
            resolve({
              base64: canvas.toDataURL('image/jpeg', 1.0),
              height: 595.28,
              width: 595.28 / contentHeight * contentWidth
            })
          }).catch(err => {
            reject(err)
          })
        }),
        new Promise((resolve, reject) => {
          html2canvas(this.$refs.container2, {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const contentWidth = canvas.width
            const contentHeight = canvas.height
            debugger
            resolve({
              base64: canvas.toDataURL('image/jpeg', 1.0),
              height: 595.28,
              width: 595.28 / contentHeight * contentWidth
            })
          }).catch(err => {
            reject(err)
          })
        })
      ]
      Promise.all(promises).then(pictures => {
        pictures.forEach((picture, index) => {
          if (index > 0) {
            pdf.addPage()
          }
          pdf.addImage(picture.base64, 'JPEG', 0, 0, picture.width, picture.width)
        })
        pdf.save('飞检成绩.pdf')
      }).finally(_ => {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      })
    },
    /**
     * 下载
     */
    download1() {
      // this.loading = false
      // const contentWidth = canvas.width
      // const contentHeight = canvas.height
      //
      // // a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
      // const imgWidth = 595.28 / contentHeight * contentWidth
      // const imgHeight = 595.28
      //
      // const pageData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = new JsPDF('l', 'pt', 'a4')

      pdf.html(
        this.$refs.textContainer, { callback: dispose => { pdf.save('Test.pdf') } },
        dispose => {
          // dispose: object with X, Y of the last line add to the PDF
          //          this allow the insertion of new lines after html
          pdf.save('飞检成绩.pdf')
        })

      // pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
    },
    /**
     * 获取检查字段集合
     * @param data 项目检查数据
     * @return {*[]}
     */
    getCheckShowFields(data) {
      const result = []
      if (data['GC-001-002-001_level']) {
        result.push({ name: '防渗漏', value: data['GC-001-002-001_level'] + '级', qualified: data['GC-001-002-001_level'] === 'A' })
      }
      if (data['GC-001-002-002_score']) {
        result.push({ name: '质量', value: data['GC-001-002-002_score'] + '分', qualified: this.valueQualified(data['GC-001-002-002_level']) })
      }
      if (data['GC-001-002-003_score']) {
        result.push({ name: '安全文明', value: data['GC-001-002-003_score'] + '分', qualified: this.valueQualified(data['GC-001-002-003_level']) })
      }
      return result
    },
    /**
     * 下载图表图片
     */
    downloadCharImage() {
      this.loading = true
      try {
        const carouselContainer = this.$refs.carousel
        const activeItem = carouselContainer.$children.find(item => item.active)
        const activePanelName = activeItem.$options.propsData.name
        let contentContainer = ''
        let imageName = ''
        switch (activePanelName) {
          case 'qualityScore':
            contentContainer = 'container1'
            imageName = '精装过程抽查成绩_1'
            break
          case 'safetyProductionScore':
            contentContainer = 'container2'
            imageName = '精装过程抽查成绩_2'
            break
          default: break
        }
        if (contentContainer) {
          html2canvas(this.$refs[contentContainer], {
            dpi: 300,
            // allowTaint: true,  //允许 canvas 污染， allowTaint参数要去掉，否则是无法通过toDataURL导出canvas数据的
            // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
            useCORS: true
          }).then(canvas => {
            const link = document.createElement('a')
            link.href = canvas.toDataURL()
            link.setAttribute('download', imageName + '.png')
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
          }).catch(err => {
            throw err
          })
        }
      } catch (e) {
        this.$message.error('生成图片异常，请刷新重试')
      } finally {
        setTimeout(_ => {
          this.loading = false
        }, 250)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrapper {
  height: calc(100% - 10px);
  width: calc(100% - 20px);
  margin: 0 10px 10px;
  padding: 10px;
  font-family: Simsun;
  display: flex;
  flex-direction: column;
  .fontBold {
    font-weight: bold;
  }
  .text-container {
    color: black;
    .text-title {
      font-size: 26px;
      text-align: center
    }
    .text-section-container {
      display: flex;
      padding: 0 20px;
      flex-wrap: wrap;
    }
    .text-section-item {
      width: 33.3%;
    }
    .text-content {
      font-size: 18px;
      margin: 5px 0;
    }
  }
  .char-container {
    flex: 1;
  }
  .text-underline {
    border-bottom: 2px solid black;
    padding-bottom: 1px;
    display:inline;
    text-decoration-color:rgba(151,151,151,.2);
  }
}

</style>
